package com.sakura.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sakura.oj.annotation.AuthCheck;
import com.sakura.oj.common.BaseResponse;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.common.ResultUtils;
import com.sakura.oj.constant.UserConstant;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.exception.ThrowUtils;
import com.sakura.oj.model.dto.tag.TagAddRequest;
import com.sakura.oj.model.dto.tag.TagQueryRequest;
import com.sakura.oj.model.dto.tag.TagUpdateRequest;
import com.sakura.oj.model.entity.Tag;
import com.sakura.oj.service.TagService;
import com.sakura.oj.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 标签接口
 *
 * @author Sakura
 */
@RestController
@RequestMapping("/tag")
@Slf4j
public class TagController {

    @Resource
    private TagService tagService;


    /**
     * 获取当前系统中全部标签列表
     *
     * @return {@link BaseResponse}<{@link List<Tag>}>
     */
    @GetMapping("all")
    public BaseResponse<List<Tag>> getTagList() {
        List<Tag> tagList = tagService.list();
        return ResultUtils.success(tagList);
    }


    // region 增删改查

    /**
     * 创建标签
     *
     * @param tagAddRequest {@link TagAddRequest}
     * @return {@link BaseResponse}<{@link Long}>
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTag(@RequestBody @Validated TagAddRequest tagAddRequest) {
        ThrowUtils.throwIf(tagAddRequest == null, ErrorCode.PARAMS_ERROR);

        Tag tag = new Tag();
        BeanUtils.copyProperties(tagAddRequest, tag);

        // 写入数据库
        boolean result = tagService.save(tag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newTagId = tag.getId();
        return ResultUtils.success(newTagId);
    }

    /**
     * 删除标签
     *
     * @param id 标签id
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteTag(@PathVariable @NotNull(message = "标签id不能为空") Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 判断是否存在
        Tag oldTag = tagService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (UserHolder.isNotAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = tagService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新标签（仅管理员可用）
     *
     * @param tagUpdateRequest {@link TagUpdateRequest}
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTag(@RequestBody @Validated TagUpdateRequest tagUpdateRequest) {
        if (tagUpdateRequest == null || tagUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Tag tag = new Tag();
        BeanUtils.copyProperties(tagUpdateRequest, tag);

        // 判断是否存在
        long id = tagUpdateRequest.getId();
        Tag oldTag = tagService.getById(id);
        ThrowUtils.throwIf(oldTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = tagService.updateById(tag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 分页获取标签列表（仅管理员可用）
     *
     * @param tagQueryRequest {@link TagQueryRequest}
     * @return {@link BaseResponse}<{@link Page<Tag>}>
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Tag>> listTagByPage(@RequestBody TagQueryRequest tagQueryRequest) {
        long current = tagQueryRequest.getCurrent();
        long size = tagQueryRequest.getPageSize();
        // 查询数据库
        Page<Tag> tagPage = tagService.page(new Page<>(current, size),
                tagService.getQueryWrapper(tagQueryRequest));
        return ResultUtils.success(tagPage);
    }

    /**
     * 分页获取标签列表（封装类）
     *
     * @param tagQueryRequest {@link TagQueryRequest}
     * @return {@link BaseResponse}<{@link Page<Tag>}>
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Tag>> listTagVOByPage(@RequestBody TagQueryRequest tagQueryRequest) {
        long current = tagQueryRequest.getCurrent();
        long size = tagQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Tag> tagPage = tagService.page(new Page<>(current, size),
                tagService.getQueryWrapper(tagQueryRequest));
        return ResultUtils.success(tagPage);
    }

    // endregion
}
